<?php

namespace App\Http\Controllers\Admin;

use App\Constants\AppConstants;
use App\Http\Controllers\Controller;
use App\Models\AfterSalesRequest;
use App\Models\AfterSalesApproval;
use App\Models\AfterSalesLogistic;
use App\Models\LogisticsCompany;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminAfterSalesController extends Controller
{
    /**
     * 售后申请列表
     */
    public function index(Request $request)
    {
        $requests = AfterSalesRequest::with(['order', 'user', 'items.orderItem.product'])
            ->when($request->status, function ($query, $status) {
                return $query->where('status', $status);
            })
            ->when($request->type, function ($query, $type) {
                return $query->where('type', $type);
            })
            ->when($request->order_number, function ($query, $orderNumber) {
                return $query->whereHas('order', function ($q) use ($orderNumber) {
                    $q->where('order_number', $orderNumber);
                });
            })
            ->when($request->search, function ($query, $search) {
                return $query->whereHas('order', function ($q) use ($search) {
                    $q->where('order_number', 'like', "%{$search}%");
                })->orWhereHas('user', function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                      ->orWhere('email', 'like', "%{$search}%");
                });
            })
            ->orderBy('created_at', 'desc')
            ->paginate(AppConstants::PAGINATION_ADMIN_DEFAULT);

        // 统计信息
        $stats = [
            'total' => AfterSalesRequest::count(),
            'pending' => AfterSalesRequest::where('status', AfterSalesRequest::STATUS_PENDING)->count(),
            'approved' => AfterSalesRequest::where('status', AfterSalesRequest::STATUS_APPROVED)->count(),
            'processing' => AfterSalesRequest::where('status', AfterSalesRequest::STATUS_PROCESSING)->count(),
            'completed' => AfterSalesRequest::where('status', AfterSalesRequest::STATUS_COMPLETED)->count(),
            'rejected' => AfterSalesRequest::where('status', AfterSalesRequest::STATUS_REJECTED)->count(),
        ];

        return Inertia::render('Admin/AfterSales/Index', [
            'requests' => $requests,
            'stats' => $stats,
            'filters' => $request->only(['status', 'type', 'search', 'order_number']),
        ]);
    }

    /**
     * 售后申请详情
     */
    public function show(AfterSalesRequest $afterSalesRequest)
    {
        $afterSalesRequest->load([
            'order.items.product',
            'order.items.variant',
            'user',
            'items.orderItem.product',
            'items.orderItem.variant',
            'approvals.admin',
            'logistics',
        ]);

        // 添加超时计算属性
        $afterSalesRequest->is_near_timeout = $afterSalesRequest->isNearTimeout();
        $afterSalesRequest->timeout_message = $afterSalesRequest->getTimeoutMessage();

        // 获取启用的物流公司
        $logisticsCompanies = LogisticsCompany::active()->ordered()->get(['id', 'name', 'code']);

        return Inertia::render('Admin/AfterSales/Show', [
            'request' => $afterSalesRequest,
            'logisticsCompanies' => $logisticsCompanies,
        ]);
    }

    /**
     * 审核售后申请
     */
    public function approve(Request $request, AfterSalesRequest $afterSalesRequest)
    {
        $request->validate([
            'approved_amount' => 'nullable|numeric|min:0|max:' . $afterSalesRequest->requested_amount,
            'admin_comment' => 'nullable|string|max:1000',
        ]);

        if ($afterSalesRequest->status !== AfterSalesRequest::STATUS_PENDING) {
            return redirect()->back()->with('error', '该申请状态不允许审核');
        }

        $approvedAmount = $request->approved_amount ?? $afterSalesRequest->requested_amount;
        $adminComment = $request->admin_comment;

        // 更新申请状态
        $afterSalesRequest->markAsApproved($approvedAmount, $adminComment);

        // 记录审批操作
        AfterSalesApproval::create([
            'request_id' => $afterSalesRequest->id,
            'admin_id' => auth()->id(),
            'action' => AfterSalesApproval::ACTION_APPROVE,
            'reason' => '审核通过',
            'comment' => $adminComment,
            'amount_adjustment' => $approvedAmount - $afterSalesRequest->requested_amount,
        ]);

        return redirect()->back()->with('success', '售后申请已通过审核');
    }

    /**
     * 拒绝售后申请
     */
    public function reject(Request $request, AfterSalesRequest $afterSalesRequest)
    {
        $request->validate([
            'rejection_reason' => 'required|string|max:1000',
        ]);

        if ($afterSalesRequest->status !== AfterSalesRequest::STATUS_PENDING) {
            return redirect()->back()->with('error', '该申请状态不允许拒绝');
        }

        // 更新申请状态
        $afterSalesRequest->markAsRejected($request->rejection_reason);

        // 记录审批操作
        AfterSalesApproval::create([
            'request_id' => $afterSalesRequest->id,
            'admin_id' => auth()->id(),
            'action' => AfterSalesApproval::ACTION_REJECT,
            'reason' => '审核拒绝',
            'comment' => $request->rejection_reason,
        ]);

        return redirect()->back()->with('success', '售后申请已拒绝');
    }

    /**
     * 开始处理售后申请
     */
    public function process(AfterSalesRequest $afterSalesRequest)
    {
        if ($afterSalesRequest->status !== AfterSalesRequest::STATUS_APPROVED) {
            return redirect()->back()->with('error', '该申请状态不允许开始处理');
        }

        // 更新申请状态
        $afterSalesRequest->markAsProcessing();

        // 记录审批操作
        AfterSalesApproval::create([
            'request_id' => $afterSalesRequest->id,
            'admin_id' => auth()->id(),
            'action' => AfterSalesApproval::ACTION_PROCESS,
            'reason' => '开始处理',
        ]);

        return redirect()->back()->with('success', '已开始处理售后申请');
    }

    /**
     * 完成售后申请
     */
    public function complete(AfterSalesRequest $afterSalesRequest)
    {
        if ($afterSalesRequest->status !== AfterSalesRequest::STATUS_PROCESSING) {
            return redirect()->back()->with('error', '该申请状态不允许完成');
        }

        // 更新申请状态
        $afterSalesRequest->markAsCompleted();

        // 记录审批操作
        AfterSalesApproval::create([
            'request_id' => $afterSalesRequest->id,
            'admin_id' => auth()->id(),
            'action' => AfterSalesApproval::ACTION_COMPLETE,
            'reason' => '处理完成',
        ]);

        // 如果是退款申请，更新订单状态
        if ($afterSalesRequest->type === AfterSalesRequest::TYPE_REFUND) {
            $afterSalesRequest->order->update([
                'payment_status' => 'refunded',
                'extended_status' => 'refunded',
            ]);
        }

        return redirect()->back()->with('success', '售后申请已完成');
    }

    /**
     * 添加物流信息
     */
    public function addLogistics(Request $request, AfterSalesRequest $afterSalesRequest)
    {
        $request->validate([
            'type' => 'required|in:return,exchange',
            'tracking_number' => 'required|string|max:255',
            'company' => 'required|string|max:255',
            'sender_name' => 'nullable|string|max:255',
            'sender_phone' => 'nullable|string|max:20',
            'sender_address' => 'nullable|string|max:500',
            'receiver_name' => 'nullable|string|max:255',
            'receiver_phone' => 'nullable|string|max:20',
            'receiver_address' => 'nullable|string|max:500',
            'note' => 'nullable|string|max:1000',
        ]);

        AfterSalesLogistic::create([
            'request_id' => $afterSalesRequest->id,
            'type' => $request->type,
            'submitted_by' => 'admin',
            'tracking_number' => $request->tracking_number,
            'company' => $request->company,
            'status' => 'pending',
            'sender_name' => $request->sender_name,
            'sender_phone' => $request->sender_phone,
            'sender_address' => $request->sender_address,
            'receiver_name' => $request->receiver_name,
            'receiver_phone' => $request->receiver_phone,
            'receiver_address' => $request->receiver_address,
            'note' => $request->note,
            'sent_at' => now(),
        ]);

        return redirect()->back()->with('success', '物流信息已添加');
    }

    /**
     * 换货流程：确认收到用户寄回的商品
     */
    public function confirmReturnReceived(AfterSalesRequest $afterSalesRequest)
    {
        if ($afterSalesRequest->type !== AfterSalesRequest::TYPE_EXCHANGE) {
            return redirect()->back()->with('error', '只有换货申请才能确认收货');
        }

        if ($afterSalesRequest->status !== AfterSalesRequest::STATUS_PROCESSING) {
            return redirect()->back()->with('error', '该申请状态不允许确认收货');
        }

        // 更新状态
        $afterSalesRequest->markReturnReceived();

        // 记录操作
        AfterSalesApproval::create([
            'request_id' => $afterSalesRequest->id,
            'admin_id' => auth()->id(),
            'action' => AfterSalesApproval::ACTION_PROCESS,
            'reason' => '确认收到用户寄回的商品',
        ]);

        return redirect()->back()->with('success', '已确认收到用户寄回的商品');
    }

    /**
     * 换货流程：寄出新商品
     */
    public function sendNewProduct(Request $request, AfterSalesRequest $afterSalesRequest)
    {
        if ($afterSalesRequest->type !== AfterSalesRequest::TYPE_EXCHANGE) {
            return redirect()->back()->with('error', '只有换货申请才能寄出新商品');
        }

        $request->validate([
            'tracking_number' => 'required|string|max:255',
            'company' => 'required|string|max:255',
            'note' => 'nullable|string|max:1000',
        ]);

        // 创建物流信息
        AfterSalesLogistic::create([
            'request_id' => $afterSalesRequest->id,
            'type' => AfterSalesLogistic::TYPE_EXCHANGE,
            'submitted_by' => AfterSalesLogistic::SUBMITTED_BY_ADMIN,
            'tracking_number' => $request->tracking_number,
            'company' => $request->company,
            'status' => 'shipped',
            'note' => $request->note,
            'sent_at' => now(),
        ]);

        // 更新状态
        $afterSalesRequest->markNewSent();

        // 记录操作
        AfterSalesApproval::create([
            'request_id' => $afterSalesRequest->id,
            'admin_id' => auth()->id(),
            'action' => AfterSalesApproval::ACTION_PROCESS,
            'reason' => '新商品已寄出',
        ]);

        return redirect()->back()->with('success', '新商品已寄出');
    }

    /**
     * 换货流程：确认新商品已送达
     */
    public function confirmNewDelivered(AfterSalesRequest $afterSalesRequest)
    {
        if ($afterSalesRequest->type !== AfterSalesRequest::TYPE_EXCHANGE) {
            return redirect()->back()->with('error', '只有换货申请才能确认送达');
        }

        if ($afterSalesRequest->status !== AfterSalesRequest::STATUS_PROCESSING) {
            return redirect()->back()->with('error', '该申请状态不允许确认送达');
        }

        // 更新状态
        $afterSalesRequest->markNewDelivered();

        // 记录操作
        AfterSalesApproval::create([
            'request_id' => $afterSalesRequest->id,
            'admin_id' => auth()->id(),
            'action' => AfterSalesApproval::ACTION_PROCESS,
            'reason' => '确认新商品已送达',
        ]);

        return redirect()->back()->with('success', '已确认新商品送达');
    }

    /**
     * 完成换货流程
     */
    public function completeExchange(AfterSalesRequest $afterSalesRequest)
    {
        if ($afterSalesRequest->type !== AfterSalesRequest::TYPE_EXCHANGE) {
            return redirect()->back()->with('error', '只有换货申请才能完成换货');
        }

        if ($afterSalesRequest->extended_status !== AfterSalesRequest::EXTENDED_STATUS_NEW_DELIVERED) {
            return redirect()->back()->with('error', '新商品必须已送达才能完成换货');
        }

        // 完成售后申请
        $afterSalesRequest->markAsCompleted();

        // 记录操作
        AfterSalesApproval::create([
            'request_id' => $afterSalesRequest->id,
            'admin_id' => auth()->id(),
            'action' => AfterSalesApproval::ACTION_COMPLETE,
            'reason' => '换货流程完成',
        ]);

        return redirect()->back()->with('success', '换货流程已完成');
    }
}
